/**
 * Radio Story Cards - using RFID tags to track physical story cards in an agile/lean environment.
 *
 * See http://www.radiostorycards.com for more information.
 *
 *
 * Copyright (C) 2011, Ted M. Young
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.radiostorycards.domain.tags;

import java.math.BigInteger;

/**
 * An immutable RFID Tag that consists of the 5-bytes from an EM4100 125KHz RFID tag or token.
 *
 * @author Ted Young <tedyoung@gmail.com> @JitterTed
 */
public class RfidTag {
  private int _tagHashCode;
  private byte[] _tagBytes;
  private String _tagString;

  public RfidTag(byte[] tagBytes) {
    init(tagBytes);
  }

  private void init(byte[] tagBytes) {
    _tagBytes = tagBytes;
    _tagHashCode = computeHashCodeFor(tagBytes);
    _tagString = ByteFormatter.formatBytes(tagBytes);
  }

  public RfidTag(int tagId) {
    _tagBytes = null;
    _tagHashCode = tagId;
    _tagString = Integer.toHexString(tagId).toUpperCase();
  }

  public RfidTag(Iterable<? extends Byte> tagAsBytes) {
    byte[] tagBytes = new byte[5];
    int index = 0;
    for (Byte aByte : tagAsBytes) {
      tagBytes[index++] = aByte;
    }
    init(tagBytes);
  }

  public byte[] getAsBytes() {
    return _tagBytes;
  }

  public String toString() {
    return _tagString;
  }

  public static int computeHashCodeFor(byte[] bytes) {
    long bytesAsLong = new BigInteger(1, bytes).longValue();
    return (int)( bytesAsLong ^ (bytesAsLong >>> 32) );
  }

  @Override
  public boolean equals(Object other) {
    if (this == other) return true;
    if (other == null || getClass() != other.getClass()) return false;
    RfidTag rfidTag = (RfidTag) other;
    return _tagHashCode == rfidTag._tagHashCode;
  }

  @Override
  public int hashCode() {
    return _tagHashCode;
  }
}
